#!/bin/bash
# centos7.9优化脚本
source /etc/rc.d/init.d/functions

# 一级菜单
menu1(){
    clear
    cat << EOF
-----------------------------------------------
|**********欢迎使用centos7.9优化脚本**********|
|*******************welcome*******************|
-----------------------------------------------
1. 一键优化
2. 自定义优化
3. 退出
EOF
    read -p "请选择[1-3]: " num1

}

# 二级菜单
menu2(){
    clear
    cat << EOF
-----------------------------------
|**********请选择【1-11】**********|
-----------------------------------
1. 关闭selinux
2. 关闭firewalld
3. 修改文件句柄数ulimit
4. 修改yum源使用阿里云yum源
5. 优化系统内核
6. 加快ssh登录速度
7. 设置时间同步
8. 关闭NetworkManager
9. 安装常用软件包
10. 返回上一层
11. 退出
EOF

    read -p "请选择需要优化项目【1-11】：" num2

}

# 1.关闭selinux
selinuxset(){
    selinux_status=`grep "SELINUX=disabled" /etc/sysconfig/selinux | wc -l`
    echo "====================禁用selinux===================="
    if [ ${selinux_status} -eq 0 ];then
        sed -i 's/enforcing/disabled/' /etc/selinux/config
        setenforce 0
        echo "# grep SELINUX=disabled /etc/sysconfig/selinux"
        grep SELINUX=disabled /etc/sysconfig/selinux
        echo "# getenforce"
        getenforce
    else
        echo "SELINUX已处于关闭状态"
        echo "# grep SELINUX=disabled /etc/sysconfig/selinux"
        grep SELINUX=disabled /etc/sysconfig/selinux
        echo "# getenforce"
        getenforce        
    fi
    action "已禁用SELINUX" /bin/true
    echo "==================================================="
    sleep 2
}

# 2.关闭firewalld
firewalldset(){
    echo "====================禁用firewalld=================="
    systemctl stop firewalld
    echo "#firewall-cmd  --state"
    firewall-cmd  --state
    systemctl disable firewalld &> /dev/null
    echo "#systemctl status firewalld"
    systemctl status firewalld
    action "已禁用firewalld" /bin/true
    echo "==================================================="
    sleep 3
}

# 3.修改文件句柄数ulimit
limitset(){
    echo "====================修改文件句柄数=================="
    cat >> /etc/security/limits.conf << EOF
* - nofile 65535
root - nproc 65535
EOF
    echo "#cat /etc/security/limits.conf"
    cat /etc/security/limits.conf
    action "已修改文件描述符" /bin/true
    echo "===================================================="
    sleep 5
}

# 4.修改yum源使用阿里云yum源
yumset(){

    echo "======================修改yum源====================="
    yum -y install wget &> /dev/null
    if [ $? -eq 0 ];then
        mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
        wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
        wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
    else
        echo "wget 安装失败";action "wget 安装失败" /bin/false
    fi

    action "已将镜像修改为阿里yum源" /bin/true
    
    echo "===================================================="

}

# 5.优化系统内核
kernelset(){
    echo "======================优化系统内核====================="
    count=`grep -v "^#" /etc/sysctl.conf  | wc -l`
    if [ $count -eq 0 ];then
        cat >>/etc/sysctl.conf<<EOF
# 禁用swap
vm.swappiness = 0
# 开启组合快捷键
kernel.sysrq = 1
# 决定检查一次相邻层记录的有效性的周期. 当相邻层记录失效时，将在给它发送数据前，再解析一次.(单位 秒)
net.ipv4.neigh.default.gc_stale_time = 120
# 不通过反向路径回溯进行源地址验证
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
# 始终使用与目的IP地址对应的最佳本地IP地址作为ARP请求的源IP地址
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.lo.arp_announce = 2
net.ipv4.conf.all.arp_announce = 2

# 配置服务器 TIME_WAIT 数量
net.ipv4.tcp_max_tw_buckets = 5000
# 此参数应该设置为1，防止SYN Flood(泛红攻击)
net.ipv4.tcp_syncookies = 1
# 用来限制过多SYN请求冲垮服务端的
net.ipv4.tcp_max_syn_backlog = 1024
# 表示回应第二个握手包（SYN+ACK包）给客户端IP后，如果收不到第三次握手包（ACK包），进行重试的次数（默认为5）
net.ipv4.tcp_synack_retries = 2
# 禁止Tcp空闲后慢启动
net.ipv4.tcp_slow_start_after_idle = 0
# 重用tcp连接
net.ipv4.tcp_tw_reuse = 1
# 防止简单的DoS攻击，设定系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上
net.ipv4.tcp_max_orphans = 262144
# 此参数表示TCP发送keepalive探测消息的间隔时间(秒)
net.ipv4.tcp_keepalive_time = 30
EOF
        sysctl -p
    else
        echo "优化项已存在，请查看手动添加" 

    fi

    action "内核优化完成" /bin/true
    echo "===================================================="
    sleep 3
}

# 6. 加快ssh登录速度
sshdset(){
    echo "=====================加速ssh登录===================="
    sed -i 's/#UseDNS yes/UseDNS no/g' /etc/ssh/sshd_config
    systemctl restart sshd
    echo "#grep UseDNS /etc/ssh/sshd_config"
    grep UseDNS /etc/ssh/sshd_config
    action "完成加快ssh登录速度" /bin/true
    echo "===================================================="
    sleep 3
}

# 7. 设置时间同步
ntpdateset(){
    echo "====================设置时间同步===================="
    yum -y install ntpdate &> /dev/null
    if [ $? -eq 0 ];then

        /usr/sbin/ntpdate ntp.aliyun.com
        echo "0 * * * * /usr/sbin/ntpdate ntp.aliyun.com &>/dev/null" >> /var/spool/cron/root
    else
        echo "ntpdate 安装失败"
    fi
    action "完成时间同步设置" /bin/true
    echo "===================================================="
    sleep 3
}

# 8. 关闭NetworkManager
networkmanagerset(){
    echo "=================关闭NetworkManager================="
    systemctl stop NetworkManager
    systemctl disable NetworkManager &> /dev/null
    action "已关闭NetworkManager" /bin/true
    echo "===================================================="
    sleep 3
}

# 9. 安装常用软件包
packageinstall(){
    echo "===================安装常用软件包==================="
    yum -y install ntpdate lsof net-tools telnet vim lrzsz tree nmap nc sysstat &> /dev/null
    action "完成常用工具安装" /bin/true
    echo "===================================================="
    sleep 3
}

cron_menu2(){
   menu2
    case $num2 in
    1)
      selinuxset
      cron_menu2
      ;;
    2)
      firewalldset
      cron_menu2
      ;;
    3)
      limitset
      cron_menu2
      ;;
    4)
      yumset
      cron_menu2
      ;;
    5)
      kernelset
      cron_menu2
      ;;
    6)
      sshdset
      cron_menu2
      ;;
    7)
      ntpdateset
      cron_menu2
      ;;
    8)
      networkmanagerset
      cron_menu2
      ;;
    9)
      packageinstall
      cron_menu2
      ;;
    10)
      main
      ;;
    11)
      exit
      ;;
    *)
      echo "请输入[1-11]: "
      sleep 5
      cron_menu2
      ;;
    esac

}

# 流程控制
main(){
    menu1
    case ${num1} in 
      1)
        selinuxset
        firewalldset
        limitset
        yumset
        kernelset
        sshdset
        ntpdateset
        networkmanagerset
        packageinstall
        read -p "有些配置需要重启服务器，现在是否重启（y/n）:" code
        if [ $code == "y" ];then
            reboot
        else
            echo "请稍后手动重启，使配置生效！！！"
        fi
        ;;
      2)
        cron_menu2
        ;;
      3)
        echo ${num1}
        exit
        ;;
      *)
        echo "请输入[1-3]: "
        main
        ;;
    esac
}

main


